const Router = require("@koa/router")
const router = new Router()
const authorization = require("../middleware/authorization")
const routes = require("./routes")
const usermodel = require("../model/user")
const menumodel = require("../model/menu")
routes.forEach(r => {
  if (r.auth) {
    router[r.method](r.path, async (ctx, next) => {
      try {
        await authorization(ctx, next)
        await r.action(ctx, next)
      } catch (e) {
        ctx.body = e
      }
    })
  } else {
    router[r.method](r.path, r.action)
  }
})
router.get("/set", async (ctx, next) => {
  try {
    let data = await usermodel.save({
      username: "fuyoo",
      password: "123456"
    })
    ctx.body = data
  } catch (e) {
    console.log(e)
    ctx.body = "保存出错"
  }
})

router.get("/find", async (ctx, next) => {
  try {
    let data = await usermodel.get("fuyoo")
    ctx.body = data
  } catch (e) {
    console.log(e)
    ctx.body = "查询出错"
  }
})

router.get("/menu/list", async (ctx, next) => {
  try {
    ctx.body = await menumodel.get()
  } catch (e) {
    ctx.body = []
  }
})

router.post("/menu/add", async (ctx, next) => {
  try {
    let data = ctx.request.body
    console.log(data)
    await menumodel.set(data)
    ctx.body = {
      code: "1",
      msg: "增加成功",
      data: null
    }
  } catch (e) {
    ctx.body = {
      code: "0",
      msg: "增加失败",
      data: null
    }
  }
})

router.get("/socket.io", async (ctx) => {
  ctx.res.writeHead("code", 200)
})
module.exports = router
